'use strict';

let fs = require('fs');
let path = require('path');
let router = require('koa-router')();

// 搜索过滤所有的路由文件
function getEachControllerFiles(dir) {
    // 2、需要过滤真正的控制器文件（是js文件，并且不是index.js）
    let files = fs.readdirSync(dir);

    let controllerFiles = files.filter((name) => {
        return name.endsWith('.js') && name !== 'index.js';
    });

    return controllerFiles;
}

// 遍历每一个路由文件，注册每一个定义的路由
function registeRoutes(files) {
    files.forEach(item => {
        let tmpFile = path.join(__dirname, item);
        let tmpRoutes = require(tmpFile);
        for (var x in tmpRoutes) {
            let valueArr = tmpRoutes[x];
            // 获得键值对中的值，里面的请求类型
            let type = valueArr[0];
            // 获取键值中的值（是一个数组），里面的处理函数
            // let fn = tmpRoutes[x][1];
            if (type === 'get') {
                if (valueArr.length === 2) {
                    let fn = valueArr[1];
                    router.get(x, fn);
                } else {
                    let auth = valueArr[1];
                    let fn = valueArr[2];
                    router.get(x, auth, fn);
                }
            }
            else if (type === 'post') {
                if (valueArr.length === 2) {
                    let fn = valueArr[1];
                    router.post(x, fn);
                } else {
                    let auth = valueArr[1];
                    let fn = valueArr[2];
                    router.post(x, auth, fn);
                }
            }
            else if (type === 'put') {
                if (valueArr.length === 2) {
                    let fn = valueArr[1];
                    router.put(x, fn);
                } else {
                    let auth = valueArr[1];
                    let fn = valueArr[2];
                    router.put(x, auth, fn);
                }
            }
            else if (type === 'delete') {
                if (valueArr.length === 2) {
                    let fn = valueArr[1];
                    router.delete(x, fn);
                } else {
                    let auth = valueArr[1];
                    let fn = valueArr[2];
                    router.delete(x, auth, fn);
                }
            }
        }
    })
}

// 3、将本文件实现为一个中间件，以便在app.js中可以直接注册使用
module.exports = function () {
    // 1、解决正确获得控制器文件夹路径
    let defaultControlleDir = __dirname;

    let controllerFiles = getEachControllerFiles(defaultControlleDir);

    registeRoutes(controllerFiles);

    return router.routes();
}